package cn.jiaqiang.chatgpt.data.domain.auth.service;


import cn.jiaqiang.chatgpt.data.domain.auth.model.entity.AuthStateEntity;
import cn.jiaqiang.chatgpt.data.domain.auth.model.valobj.AuthTypeVO;
import cn.jiaqiang.chatgpt.data.domain.auth.repository.IAuthRepository;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description 鉴权服务
 */
@Slf4j
@Service
public class AuthService extends AbstractAuthService {

    @Resource
    private IAuthRepository authRepository;

    @Override
    protected AuthStateEntity checkCode(String code) {
        // 通过 code 获取 openID
        String openId = authRepository.getOpenIdByUserCode(code);
        // 通过 openId 获取 userId
        String userId = authRepository.getUserIdByOpenId(openId);
        // 通过 userid 获取 code
        String redisCode = authRepository.getRedisCodeByUSerId(userId);
        // 获取验证码校验
        if (openId == null || userId == null || !code.equals(redisCode)){
            log.info("鉴权, 用户收入的验证码不存在 {}", code);
            return AuthStateEntity.builder()
                    .code(AuthTypeVO.A0001.getCode())
                    .info(AuthTypeVO.A0001.getInfo())
                    .build();
        }

        // 移除缓存Key值
        authRepository.removeCodeAndUserId(code, userId, openId);
        // 验证码校验成功
        log.info("鉴权, 用户收入的验证码校验成功 {}", code);
        // 校验成功
        return AuthStateEntity.builder()
                .code(AuthTypeVO.A0000.getCode())
                .info(AuthTypeVO.A0000.getInfo())
                .openId(openId)
                .userId(userId)
                .build();
    }

    @Override
    public boolean checkToken(String token) {
        return isVerify(token);
    }

    @Override
    public String openid(String token) {
        try {
            Claims claims = decode(token);
            return claims.get("openId").toString();
        } catch (Exception e) {
            log.error("解析 openid 出错: ", e);
            return null;
        }
    }

    @Override
    public String userId(String token) {
        try {
            Claims claims = decode(token);
            return claims.get("userId").toString();
        } catch (Exception e) {
            log.error("解析 openid 出错: ", e);
            return null;
        }
    }

}
